import sys
import random
import string

WORD_SIZE = 4
BUFFER_SIZE = 16 * 1024


def generate_alphabet(size):
    return string.digits[:size]


def generate_index(alphabet, word_size):
    if word_size == 1:
        return alphabet
    index = []
    for a in alphabet:
        for d in generate_index(alphabet, word_size - 1):
            index.append('{0}{1}'.format(a, d))
    return index


def random_string(length, index):
    word_size = len(index[0])
    num_substrings = length // word_size
    substrings = [random.choice(index) for i in range(num_substrings)]
    return ''.join(substrings)


if __name__ == '__main__':
    if len(sys.argv) != 4:
        print("usage:")
        print("{0} file_name file_size alphabet_size".format(sys.argv[0]))
        print("file_size in MB")
    else:
        try:
            file_name = sys.argv[1]
            file_size = int(sys.argv[2]) * 1024 * 1024
            alphabet_size = int(sys.argv[3])
            if not(0 < alphabet_size < 10) or file_size < 1:
                raise ValueError
        except:
            print("file_size must be a positive integer")
            print("alphabet_size must be 0-9")
        else:
            alphabet = generate_alphabet(alphabet_size)
            index = generate_index(alphabet, WORD_SIZE)
            iterations = file_size // BUFFER_SIZE
            f = open(file_name, 'w')
            for i in range(iterations):
                f.write(random_string(BUFFER_SIZE, index))
